package com.yingxin.yxerp.module.organization.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yingxin.yxerp.module.organization.entity.User;
import com.yingxin.yxerp.module.organization.entity.UserAppRole;
import com.yingxin.yxerp.module.organization.mapper.UserAppRoleMapper;
import com.yingxin.yxerp.module.organization.service.IUserAppRoleService;
import com.yingxin.yxerp.module.permission.entity.AppRole;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 用户-角色 服务实现类
 * @author fanchao
 * @since 2021-05-10
 */

@Service
public class UserAppRoleServiceImpl extends ServiceImpl<UserAppRoleMapper, UserAppRole> implements IUserAppRoleService {

    /**
     * 根据 userId 查询
     */
    @Override
    public List<UserAppRole> listByUserId(String userId) {
        QueryWrapper<UserAppRole> qw = new QueryWrapper<>();
        qw.lambda().eq(UserAppRole::getUserId, userId);
        return list(qw);
    }


    // @OplogAnnotation(biz = BusinessType.USER, id = "{{user.id}}",  action = "删除所有角色", desc = "用户[{{user.staffName}} {{user.staffNo}}]，删除所有角色")
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public Boolean deleteByUserId(User user) {
        UpdateWrapper<UserAppRole> uw = new UpdateWrapper<>();
        uw.lambda().eq(UserAppRole::getUserId, user.getId());
        return remove(uw);
    }

    // @OplogAnnotation(biz = BusinessType.USER, id = "{{user.id}}",  action = "设置角色", desc = "用户[{{user.staffName}} {{user.staffNo}}]，角色[{{role.name}}]")
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void create(User user, AppRole role) {
        UserAppRole userRole = new UserAppRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(role.getId());
        save(userRole);
    }
}
